package cn.mybatis;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * SqlSession工具类
 *
 * @author zhang peng yang ming
 * @create 2018-07-22 17:02
 */
public class SqlSessionFactoryUtil {
    // session对象
    private static SqlSessionFactory sqlSessionFactory;

    /**
     * 构造SqlSessionFactory
     * @return
     */
    public static SqlSessionFactory initSessionFactory() {
        // mybatis资源路径
        String resource = "cn/mybatis/configuration.xml";
        InputStream configuration = null;
        try {
            // 获取mybatis资源流
            configuration = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 双检锁/双重校验锁
        synchronized (SqlSessionFactoryUtil.class) {
            if (sqlSessionFactory == null) {
                // 通过 SqlSessionFactoryBuilder 获得 SqlSessionFactory
                sqlSessionFactory =  new SqlSessionFactoryBuilder().build(configuration);
            }
        }

        return sqlSessionFactory;
    }

    /**
     * 获取session
     * @return
     */
    public static SqlSession openSession() {
        if (sqlSessionFactory == null) {
            initSessionFactory();
        }

        return sqlSessionFactory.openSession();
    }

    
}
